if (window.plus) {
	ready();
} else {
	document.addEventListener('plusready', ready, false);
}

$(function() {
	if (AGENT_CLIENT.WEB) {
		ready();
	}
})


function ready() {
	var
		_user, //用户信息
		_query = {
			index: 1,
			size: CONFIG_MANAGER.pageSize,
			query: "",
			search: {
				type: 1
			}
		}, //搜索条件·
		_html = [], //html字符串
		_myScroll, //滚动
		_thispage, //当前页
		_pullUp, //上拉
		_pullDown, //下拉
		_translateX //计算偏移值
	;
	var ordersPage = function() {
		this.init();
	};
	ordersPage.prototype = {
		init: function() {
			this.addScroll();
			this.loadData();
			this.bindEvent();
		},
		addScroll: function() {
			_pullUp = $("#pullUp");
			_pullDown = $("#pullDown");
			_myScroll = new IScroll('#wrapper', {
				probeType: 2,
				scrollbars: true,
				mouseWheel: false,
				fadeScrollbars: true,
				bounce: true,
				interactiveScrollbars: false,
				shrinkScrollbars: 'scale',
				click: true,
				keyBindings: true,
				momentum: true
			});
			_myScroll.on("scrollEnd", function() {
				//console.log("this.y=" + this.y);
				//console.log("this.maxScrollY=" + this.maxScrollY);
				//console.log(this);
				//console.dir(this.maxScrollY);
				//              if(!_pullUp.is(':hidden') || !_pullDown.is(":hidden")){
				//              	return false;
				//              }
				if ((this.y < 0) && (this.y == this.maxScrollY)) {
					console.log("滚动到底部");
					_pullUp.show();
					setTimeout(function() {
						_query.index++;
						_thispage.loadOrders("add");
					}, 100);
				} else if ((this.y == 0) && (this.y != this.maxScrollY)) {
					console.log("滚动到顶部");
					_pullDown.show();
					setTimeout(function() {
						_query.index = 1;
						_thispage.loadOrders("renovate");
					}, 100);
				}
			});
		},
		//加载
		loadData: function() {
			_user = getLocalStorage(STORAGE_MANAGER.user);
			if (!_user) {
				redirect("../account/login.html");
				return false;
			}
			var statusString = getUrlParam("type");
			if (statusString) {
				_query.search.status = this.getSearchstatus(statusString);
				this.moveOrderTab(statusString);
			}
			this.loadOrders();
		},
		loadOrders: function(action) {
			var requestUrl = CONFIG_MANAGER.RequstUrl + "v1/orders/my/" + _user.id;
			$.ajax({
				type: "POST",
				url: requestUrl,
				contentType: 'application/json',
				data: JSON.stringify(_query),
				async: true,
				headers: {
					"token": _user.token
				},
				beforeSend: function() {
					_pullDown.show();
				}
			}).done(function(data) {
				_thispage.loadList(data, action);
			}).fail(function(data) {
				$.toast(data);
			}).always(function() {});
		},
		//加载列表
		loadList: function(data, action) {
			data = JSON.parse(data);
			var length = data.data.length,
				list = data.data,
				_html = [];
			if (undefined == action && 0 == length) {
				$("#orderList").html('<div class="zhanwushuju"><img src="../../images/zanwushuju.png"><br>暂无数据</div>');
			} else {
				$.each(list, function(i, order) {
					_html.push('<div name="divOrder" tip="' + order.order_no + '" class="bgai ddnybg">');
					//订单编号
					_html.push('<div class="ddnybbt mbbottom">');
					_html.push('<p class="dfktbdw">' + order.status_text + '</p>');
					_html.push('<p class="dddpt"><span>订单号：<b>' + order.id + '</b></span>' + order.shop_name + '</p>');
					_html.push('</div>');
					//订单商品
					$.each(order.items, function(j, goods) {
						_html.push('<div class="mbbottom with100 overflow">');
						_html.push('<dl class="cpxqxztop cpxqxztop1 mtop0">');
						var imageUrl = ("" == goods.logo) ? "../../images/orderlogo.png" : getImageUrl(goods.logo, 65, 66);
						_html.push('<dt><img src="' + imageUrl + '" /></dt>');
						_html.push('<dd>');
						_html.push('<p class="floatr">');
						_html.push('<span class="money">&yen;' + goods.act_price + '</span>');
						_html.push('+');
						_html.push('<span class="jinbi"><b><img src="../../images/jbtub.jpg"></b>' + goods.coin + '</span>');
						_html.push('</p>');
						_html.push(goods.sku_name);
						_html.push('</dd>');
						_html.push('<dd class="huisezi"><span class="x2">x' + goods.qty + '</span>' + goods.specs + '</dd>')
						_html.push('</dl>');
						_html.push('</div>');
					});
					//
					_html.push('<div class="gjjsl">');
					_html.push('<p class="floatr">');
					_html.push('<span class="money">&yen' + order.pay_fee + '</span>');
					_html.push('+');
					_html.push('<span class="jinbi">');
					_html.push('<b><img src="../../images/jbtub.jpg"></b>' + order.discount_fee);
					_html.push('</span>');
					_html.push('</p>共计' + order.items.length + '件商品(邮费：&yen' + order.delivery_fee + ')');
					_html.push('</div>');
					//操作

					var operations = getOrderOperation(order.status, order.comment);
					if (null != operations && operations.length > 0) {
						_html.push('<p class="ddczan">');
						$.each(operations, function(i, item) {
							var orderItem = {
								"ops": item.key,
								"id": order.id,
								"mainorderno":order.main_order_no,
							};
							//console.log(order.id);
							_html.push('<span name="orderOps" tip=' + JSON.stringify(orderItem));
							if ('cancel' == item.key) {
								_html.push(' class="huangsebg_gray">');
							} else {
								_html.push(' class="huangsebg">');
							}
							_html.push(item.text);
							_html.push('</span>');
						});
						_html.push('</p>');
					}
					_html.push('</div>');
				});
				if ("add" == action) {
					$(_html.join('')).appendTo($("#orderList"));
				} else {
					$("#orderList").html(_html.join(''));
				}
			}
			//加载完成后隐藏上拉下拉提示
			setTimeout(function() {
				_myScroll.refresh();
				_pullUp.hide();
				_pullDown.hide();
			}, 300);
		},
		//页面事件
		bindEvent: function() {
			//点击后退
			$("#back").on("click", function() {
				if (AGENT_CLIENT.APP) {
					plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
					plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(4)");
				} else {
					redirect("../mine/mylife.html");
				}
			});

			//点击遮罩搜索图标，显示遮罩
			$("#search_icon").on("click", function() {
				$("#searchiframe").show();
				searchiframe.window.loadSearchHistory();
			});

			//点击线上线下切换,更新搜索条件
			$("#online_offline i").on("click", function() {
				$(this).siblings().removeClass("xuanz");
				$(this).addClass("xuanz");
				_query.search.type = $(this).attr('tip');
				_thispage.loadOrders();
			});

			//点击订单类型，更新搜索条件
			$("#orderType>li").on("click", function() {
				var tip = $(this).attr("tip");
				_thispage.moveOrderTab(tip);
				_query.index = 0;
				_query.search.status = _thispage.getSearchstatus(tip);
				console.log(JSON.stringify(_query));
				_thispage.loadOrders();
			});

			//点击订单查看订单详情
			var ti = null;
			$("#orderList").on("click", "div[name='divOrder']>div", function() {
				if (t1 == null) {
					t1 = new Date().getTime();
				} else {
					var t2 = new Date().getTime();
					if (t2 - t1 < 500) {
						t1 = t2;
						return;
					} else {
						t1 = t2;
					}
				}
				var mainorderno = $(this).parent().attr("tip");
				redirect("detail.html?mainorderno=" + mainorderno);
			});

			//订单操作
			t1 = null;
			$("body").on("click", "span[name='orderOps']", function() {
				var that = this;
				if (t1 == null) {
					t1 = new Date().getTime();
				} else {
					var t2 = new Date().getTime();
					if (t2 - t1 < 500) {
						t1 = t2;
						return;
					} else {
						t1 = t2;
					}
				}
				var orderItem = JSON.parse($(this).attr("tip"));
				operateOrder(orderItem);
				if (['cancel'].indexOf(orderItem.ops) > -1) {
					$(that).parent().parent().remove();
					setTimeout(function() {
						_myScroll.refresh();
						_pullUp.hide();
						_pullDown.hide();
					}, 300);					
				} else if (['confirmDelivery'].indexOf(orderItem.ops) > -1) {
					_query.search.status = _thispage.getSearchstatus('finish');
					_thispage.moveOrderTab('finish');
					_thispage.loadOrders();					
				}
			});

		},
		//根据状态设置订单tab下面的那个黄色
		moveOrderTab: function(tip) {
			var li = $("li[tip='" + tip + "']");
			var value = "translateX(" + $(li).offset().left + "px)";
			$("#bottowtab").css({
				"margin-left": value,
				"transform": value,
				"-moz-transform": value,
				"-webkit-transform": value,
				"-o-transform": value,
				"-ms-transform": value
			});
		},
		//获取订单状态值
		getSearchstatus: function(statusString) {
			var status = '';
			//搜索条件，订单状态
			switch (statusString) {
				//全部
				case "all":
					status = "";
					break;
					//待付款 包含0-新订单，1-系统确认订单，
				case "unpay":
					status = 1;
					break;
					//待发货  包含2-在线支付完成，5-仓库已接收（商家确认、仓库确认），6-商品打包中 ，7-发货中
				case "pay":
					status = 2;
					break;
					//交易完成 包含，10-退款成功，11-退款失败，8-客户已收货
				case "finish":
					status = 4;
					break;
					//取消交易 包含3-已取消订单，9-正在退款
				case "cancel":
					status = 6;
					break;
				default:
					break;
			}
			return status;
		},
	};
	_thispage = new ordersPage();
	search = function(searchword) {
		_query.query = searchword.replace(/(^\s+)|(\s+$)/g, "");
		_thispage.loadOrders();
	}
}

// 关闭搜索页
function closeSearchPage() {
	$("#searchiframe").hide();
}
// 搜索
function search(searchword) {}